<!DOCTYPE html>
<html lang="en">
  <head>
    <title>图片切换</title>
    <style>
      #outer {
        width: 500px;
        margin: 10px auto;
        padding: 10px;
        background-color: burlywood;
        text-align: center;
      }
      #outer img {
        width: 450px;
        height: 300px;
      }
    </style>
  </head>
  <body>
    <div id="outer">
      <p id="text"></p>
      <img src="images/img1.png" />
      <br />
      <br />
      <button id="prev">上一张</button>
      <button id="next">下一张</button>
    </div>

    <script type="module">
      window.onload = function () {
        var imagesArr = ["images/img1.png", "images/img2.jpg", "images/img3.jpg", "images/img4.png", "images/img5.jpg"];
        var img = document.getElementsByTagName("img")[0];
        var text = document.getElementById("text");
        var index = 0;

        text.innerHTML = `一共有${imagesArr.length}张照片，目前是第${index + 1}`;

        var prev = document.getElementById("prev");
        var next = document.getElementById("next");

        prev.onclick = function () {
          index--;
          if (index < 0) {
            index = imagesArr.length - 1;
          }
          img.src = imagesArr[index];
          text.innerHTML = `一共有${imagesArr.length}张照片，目前是第${index + 1}`;
        };

        next.onclick = function () {
          index++;
          if (index > imagesArr.length - 1) {
            index = 0;
          }
          img.src = imagesArr[index];

          text.innerHTML = `一共有${imagesArr.length}张照片，目前是第${index + 1}`;
        };
      };
    </script>
  </body>
</html>
